package com.itggm.intcepters;

import cn.hutool.json.JSONUtil;

import com.alibaba.druid.util.StringUtils;
import com.itggm.response.ResponseResult;
import org.springframework.web.servlet.HandlerInterceptor;
import com.itggm.response.ResponseStatus;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

 /**
  * @Author: ggm
  * @date:  2024/11/24
  */

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        String authentication = (String) session.getAttribute("authentication");
        if (StringUtils.isEmpty(authentication)){   // 没有认证
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            ResponseResult msg = ResponseResult.fail().code(ResponseStatus.NOT_LOGIN).message(ResponseStatus.NOT_LOGIN.getMessage());
            writer.write(JSONUtil.toJsonStr(msg));
            writer.close();
           /* //如果没登陆跳转到404提示界面
            response.sendRedirect("/page/404.html");*/
            return  false;
        }
        return  true;
    }
}
